subroutine iqbalance(c0,gain,phase,nfft,istep,coverlap,c1)

! Apply amplitude and phase corrections to I/Q data using FFTs and
! "overlap-and-add" algorithm.

  parameter (MAXFFT=32768,MAXNH=MAXFFT/2)
  complex c0(0:MAXFFT-1)              !Input data
  complex c1(0:MAXFFT-1)              !Corrected data
  complex coverlap(0:MAXNH-1)         !Storage for overlap regions
  complex c(0:MAXFFT-1)
  complex ctmp(0:MAXFFT-1)
  complex h,u,v
  complex h2,z,zsum,zave
  data nn/0/
  save
  
  if(nn.eq.0) then
     fac=1.0/nfft
     zsum=0.
  endif
  nn=nn+1

  c(0:istep-1)=fac*c0(0:istep-1)      !Copy this data segment into c
  c(istep:nfft-1)=0.                  !Zero-pad to length nfft

  call four2a(c,NFFT,1,-1,1)          !Forward FFT

  smax=0.
  ipk=0
  do i=0,nfft-1                       !Find strongest signal
     s=real(c(i))**2 + aimag(c(i))**2
     if(s.gt.smax) then
        smax=s
        ipk=i
     endif
  enddo
  p=smax + real(c(nfft-i))**2 + aimag(c(nfft-i))**2
  z=c(ipk)*c(nfft-ipk)/p              !Synchronous detection of image
  zsum=zsum+z
  zave=zsum/nn
  tmp=sqrt(1.0 - (2.0*real(zave))**2)
  phase2=asin(2.0*aimag(zave)/tmp)    !Estimate phase
  gain2=tmp/(1.0-2.0*real(zave))      !Estimate gain
  h2=gain2*cmplx(cos(phase2),sin(phase2))
  freq=i*96000.0/nfft
  if(i.gt.nh)   freq=(i-nfft)*96000.0/nfft
  write(*,3001) nn,freq,gain2,phase2*57.2957795
3001 format(i5,f10.2,2f10.4)

  h=gain*cmplx(cos(phase),sin(phase))
  do i=0,nfft-1
     u=fac*c(i)
     if(i.gt.0) v=fac*c(nfft-i)
     x=real(u)  + real(v)  - (aimag(u) + aimag(v))*aimag(h) +         &
          (real(u) - real(v))*real(h)
     y=aimag(u) - aimag(v) + (aimag(u) + aimag(v))*real(h)  +         &
          (real(u) - real(v))*aimag(h)
     ctmp(i)=cmplx(x,y)
  enddo
!  ctmp(0)=0.
  c(0:nfft-1)=ctmp(0:nfft-1)
  call four2a(c,NFFT,1,1,1)                 !Inverse FFT

  c(0:NFFT-istep-1)=c(0:NFFT-istep-1)+coverlap(0:NFFT-istep-1) !Add last 
                                            !segment's overlap to this segment
  coverlap(0:NFFT-istep-1)=c(istep:NFFT-1)  !Save the samples that will overlap 
                                            !the next segment
  c1(0:istep-1)=c(0:istep-1)                !Copy good results into c1

  return
end subroutine iqbalance
